package com.tgpms.web.earlierStage.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.tgpms.web.earlierStage.controller.UpdateUseCodeTask;
import com.tgpms.web.earlierStage.dao.ObsInfoMapper;
import com.tgpms.web.earlierStage.entity.ObsInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.util.Common;
import com.tgpms.web.earlierStage.dao.ProjectInfoMapper;
import com.tgpms.web.earlierStage.entity.ProjectInfo;
import com.tgpms.web.earlierStage.service.EarlierProjectInfoService;

import javax.annotation.Resource;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class EarlierProjectInfoServiceImpl implements EarlierProjectInfoService {
	
	private final Logger log = LoggerFactory.getLogger(EarlierProjectInfoServiceImpl.class);
	
	@Autowired
	private ProjectInfoMapper projectInfoMapper;

	@Resource
	private ObsInfoMapper obsInfoMapper;
	
	//定时更新应思项目信息到表
	@Override
	public void updateUseCode() throws Exception {
		//查询userdcode为空的数据集合
		Map<String, Object> map= new HashMap<String, Object>();
		map.put("USEDCODE", "0");
		List<Map<String, Object>> list = projectInfoMapper.selProjectInfo(map);
		if(list==null || list.size()<=0) {
			log.info("没有需要更新的项目信息");
		}else {
			for(Map<String, Object> m : list) {
				log.info("当前需要更新的项目信息为："+m.toString());
				String code = m.get("PROJECT").toString();
				if(m.get("SUB_PROJECT")!=null) {
					code=code+m.get("SUB_PROJECT").toString();
				}
				if(m.get("CWP_CODE")!=null) {
					code=code+m.get("CWP_CODE").toString();
				}
				//查询英思是否有对应项目信息
				List<Map<String, Object>> plist = projectInfoMapper.getEarlierstageProjectByCode(code);
				if(plist==null || plist.size()<=0) {
					log.info("在英思没有查询到对应的项目信息");
					continue;
				}
				if(plist.size()>1) {
					log.info("在英思查询到对应的项目信息不止1条");
					continue;
				}
				Map<String, Object> pm = plist.get(0);
				log.info("在英思查询到对应的项目信息为："+pm.toString());
				//更新英思的信息到项目表
				ProjectInfo info = new ProjectInfo();
				info.setPiId(m.get("PI_ID").toString());
				info.setUsedcode(pm.get("ID").toString());
				if(!Common.isEmpty(pm.get("RHQNAME"))) {
					info.setProjectDept(pm.get("RHQNAME").toString());
				}
				if(!Common.isEmpty(pm.get("OWNER"))) {
					info.setOwnerName(pm.get("OWNER").toString());
				}
				if(!Common.isEmpty(pm.get("EXCUTE_DEPTNAME"))) {
					info.setRunCompany(pm.get("EXCUTE_DEPTNAME").toString());
				}
				if(!Common.isEmpty(pm.get("PROVINCENAME"))) {
					info.setProjectProvince(pm.get("PROVINCENAME").toString());
				}
				if(!Common.isEmpty(pm.get("CITYNAME"))) {
					info.setProjectCity(pm.get("CITYNAME").toString());
				}
				if(!Common.isEmpty(pm.get("PLAN_START_DATE"))) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					info.setPlanStartDate(sdf.parse(pm.get("PLAN_START_DATE").toString()));
				}
				if(!Common.isEmpty(pm.get("PLAN_END_DATE"))) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					info.setPlanEndDate(sdf.parse(pm.get("PLAN_END_DATE").toString()));
				}
				if(!Common.isEmpty(pm.get("PROJECT_TYPE"))) {
					info.setProjectType(pm.get("PROJECT_TYPE").toString());
				}
				if(!Common.isEmpty(pm.get("PROJECT_LINGYU"))) {
					info.setDomain(pm.get("PROJECT_LINGYU").toString());
				}
				if(!Common.isEmpty(pm.get("SIGNING_SUBJECT"))) {
					info.setSigningBody(pm.get("SIGNING_SUBJECT").toString());
				}
				if(!Common.isEmpty(pm.get("SOURCE_FUNDS"))) {
					info.setSourceOfFunds(pm.get("SOURCE_FUNDS").toString());
				}
				if(!Common.isEmpty(pm.get("FINANCING_RATIO"))) {
					String FINANCING_RATIO = pm.get("FINANCING_RATIO").toString().replaceAll(" ", "");
					if(pm.get("FINANCING_RATIO").toString().indexOf("%")>0) {
						info.setFinancingRatio(new BigDecimal(FINANCING_RATIO.replaceAll("%", "")));
					}else {
						info.setFinancingRatio(new BigDecimal(FINANCING_RATIO.toString()));
					}
				}
				if(!Common.isEmpty(pm.get("PROPORTION_FUNDS"))) {
					String PROPORTION_FUNDS = pm.get("PROPORTION_FUNDS").toString().replaceAll(" ", "");
					if(pm.get("PROPORTION_FUNDS").toString().indexOf("%")>0) {
						info.setOwnAssets(new BigDecimal(PROPORTION_FUNDS.replaceAll("%", "")));
					}else {
						info.setOwnAssets(new BigDecimal(PROPORTION_FUNDS));
					}
				}
				if(!Common.isEmpty(pm.get("PROJECT_INVEST"))) {
					info.setEstimatedInvestment(new BigDecimal(pm.get("PROJECT_INVEST").toString()));
				}
				if(!Common.isEmpty(pm.get("KEY"))) {
					info.setKeyYn(pm.get("KEY").toString());
				}
				int i = projectInfoMapper.updateByPrimaryKeySelective(info);
				if(i==1) {
					log.info("更新项目信息成功");
				}else {
					log.info("更新项目信息失败");
				}
			}
		}
	}

	
	/**
	 *增加项目信息
	 */
	@Override
	public Result addProjectInfo(ProjectInfo projectInfo, Result result) {
		//查询三个唯一键是否重复
		if(projectInfoMapper.selByUniqueKey(projectInfo.getObsCode())!=null) {
			result.setSuccess(false);
			result.setMsg("该组织机构已经挂接了项目，请勿重复挂接");
			return result;
		}
		//主键形式 yyyyMMddHHmmss+UUID 
		projectInfo.setPiId(Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
		projectInfo.setObsProject(projectInfo.getPiId());
		projectInfo.setRowstamp(projectInfo.getPiId());
		projectInfo.setInsertDate(new Date());
		int i = projectInfoMapper.insertSelective(projectInfo);
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
			result.setData(projectInfo.getPiId());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		}
		return result;
	}

	@Override
	public Result updateProjectInfo(ProjectInfo projectInfo, Result result) {
		projectInfo.setModifyDate(new Date());
		int i = projectInfoMapper.updateByPrimaryKeySelective(projectInfo);
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
		}
		return result;
	}

	@Override
	public Result deleteProjectInfo(String Id, Result result) {
		int i = projectInfoMapper.deleteByPrimaryKey(Id);
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> selProjectInfoForTree(String usersId, Result result) {
		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("obsCode", null);
		if(usersId!=null) {
			map.put("usersId", usersId);
		}
		List<Map<String, Object>> maps = projectInfoMapper.selProjectInfoTreeList(map);
		if(maps != null && maps.size()>0) {
			for(Map<String, Object> pmap : maps) {
				Map<String, Object> tempMap = new HashMap<>();
				tempMap.put("code", pmap.get("OBS_INFO_CODE").toString());
				tempMap.put("label", pmap.get("DESCRIPTION").toString());
				if (null != pmap.get("OBS_TYPE")) {
					tempMap.put("obsType", pmap.get("OBS_TYPE").toString());
				}
				if (null != pmap.get("OBS_PROJECT")) {
					tempMap.put("project", pmap.get("OBS_PROJECT").toString());
				}
				if (null != pmap.get("OBS_PROJECT_NAME")) {
					tempMap.put("projectName", pmap.get("OBS_PROJECT_NAME").toString());
				}
				List<Map<String, Object>> children = getProjectInfoChildren(usersId, pmap.get("OBS_INFO_CODE").toString());
				tempMap.put("children", children);
				list1.add(tempMap);
			}
		}
		return list1;
	}

	@Override
	public List<Map<String, Object>> selAllProjectInfoForTree(Result result) {
		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("obsCode", null);
		List<Map<String, Object>> maps = projectInfoMapper.selAllProjectInfoTreeList(map);
		if(maps != null && maps.size()>0) {
			for(Map<String, Object> pmap : maps) {
				Map<String, Object> tempMap = new HashMap<>();
				tempMap.put("code", pmap.get("OBS_CODE").toString());
				tempMap.put("label", pmap.get("DESCRIPTION").toString());
				if (null != pmap.get("OBS_TYPE")) {
					tempMap.put("obsType", pmap.get("OBS_TYPE").toString());
				}
				if (null != pmap.get("OBS_PROJECT")) {
					tempMap.put("project", pmap.get("OBS_PROJECT").toString());
				}
				if (null != pmap.get("OBS_PROJECT_NAME")) {
					tempMap.put("projectName", pmap.get("OBS_PROJECT_NAME").toString());
				}
				List<Map<String, Object>> children = getAllProjectInfoChildren(pmap.get("OBS_CODE").toString());
				tempMap.put("children", children);
				list1.add(tempMap);
			}
		}
		return list1;
	}

	@Override
	public ProjectInfo selProjectInfoByCondition(String projectId) {
		return projectInfoMapper.selectByPrimaryKey(projectId);
	}

	private List<Map<String, Object>> getAllProjectInfoChildren(String obsCode) {
		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("obsCode", obsCode);
		List<Map<String, Object>> maps = projectInfoMapper.selAllProjectInfoTreeList(map);
		if(maps != null && maps.size()>0) {
			for(Map<String, Object> pmap : maps) {
				Map<String, Object> tempMap = new HashMap<>();
				tempMap.put("code", pmap.get("OBS_CODE").toString());
				tempMap.put("label", pmap.get("DESCRIPTION").toString());
				if (null != pmap.get("OBS_TYPE")) {
					tempMap.put("obsType", pmap.get("OBS_TYPE").toString());
				}
				if (null != pmap.get("OBS_PROJECT")) {
					tempMap.put("project", pmap.get("OBS_PROJECT").toString());
				}
				if (null != pmap.get("OBS_PROJECT_NAME")) {
					tempMap.put("projectName", pmap.get("OBS_PROJECT_NAME").toString());
				}
				List<Map<String, Object>> children = getAllProjectInfoChildren(pmap.get("OBS_CODE").toString());
				tempMap.put("children", children);
				list1.add(tempMap);
			}
		}
		return list1;
	}

	private List<Map<String, Object>> getProjectInfoChildren(String usersId, String obsCode) {
		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("obsCode", obsCode);
		if(usersId!=null) {
			map.put("usersId", usersId);
		}
		List<Map<String, Object>> maps = projectInfoMapper.selProjectInfoTreeList(map);
		if(maps != null && maps.size()>0) {
			for(Map<String, Object> pmap : maps) {
				Map<String, Object> tempMap = new HashMap<>();
				tempMap.put("code", pmap.get("OBS_INFO_CODE").toString());
				tempMap.put("label", pmap.get("DESCRIPTION").toString());
				if (null != pmap.get("OBS_TYPE")) {
					tempMap.put("obsType", pmap.get("OBS_TYPE").toString());
				}
				if (null != pmap.get("OBS_PROJECT")) {
					tempMap.put("project", pmap.get("OBS_PROJECT").toString());
				}
				if (null != pmap.get("OBS_PROJECT_NAME")) {
					tempMap.put("projectName", pmap.get("OBS_PROJECT_NAME").toString());
				}
				List<Map<String, Object>> children = getProjectInfoChildren(usersId, pmap.get("OBS_INFO_CODE").toString());
				tempMap.put("children", children);
				list1.add(tempMap);
			}
		}
		return list1;
	}


//	@Override
//	public List<Map<String, Object>> selProjectInfoForTree(Result result) {
//		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
//		//分组查询第一层
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("param", " PROJECT,PROJECT_NAME ");
//		map.put("groupby", " group by PROJECT,PROJECT_NAME");
//		List<Map<String, Object>> onelist = projectInfoMapper.selProjectInfo(map);
//		if(onelist==null || onelist.size()==0) {
//			return list1;
//		}
//		for(Map<String, Object> pmap : onelist) {
//			pmap.put("code", pmap.get("PROJECT").toString());
//			pmap.put("label", pmap.get("PROJECT_NAME").toString());
//			List<Map<String, Object>> list2 = new ArrayList<Map<String,Object>>();
//			//查询第二层
//			map.clear();
//			map.put("param", " SUB_PROJECT,SUB_PROJECT_NAME ");
//			map.put("project", pmap.get("PROJECT").toString());
//			map.put("groupby", " group by SUB_PROJECT,SUB_PROJECT_NAME");
//			List<Map<String, Object>> twolist = projectInfoMapper.selProjectInfo(map);
//			if(twolist==null || twolist.size()==0) {
//				pmap.put("children", list2);
//				list1.add(pmap);
//				return list1;
//			}
//			else {
//				for(Map<String, Object> tmap : twolist) {
//					tmap.put("code", tmap.get("SUB_PROJECT").toString());
//					tmap.put("label", tmap.get("SUB_PROJECT_NAME").toString());
//					//查询第三层
//					map.clear();
//					map.put("project", pmap.get("PROJECT").toString());
//					map.put("subProject", tmap.get("SUB_PROJECT").toString());
//					List<Map<String, Object>> threelist = projectInfoMapper.selProjectInfo(map);
//					if(threelist==null || threelist.size()==0) {
//						tmap.put("children", "[]");
//					}else {
//						for(Map<String, Object> thmap : threelist) {
//							thmap.put("code", thmap.get("CWP_CODE").toString());
//							thmap.put("label", thmap.get("CWP_NAME").toString());
//						}
//					}
//					tmap.put("children", threelist);
//					list2.add(tmap);
//				}
//			}
//			pmap.put("children", list2);
//			list1.add(pmap);
//		}
//		return list1;
//	}

	
}
